package utils

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/pkg/errors"
	"time"
)

type UserToken struct {
	jwt.StandardClaims
	//自定义用户信息
	UserId int64 `json:"userid"`
}

// 生成token
func GenToken(UserId int64, expireDuration time.Duration, secrite_key []byte) (string, error) {
	user := UserToken{
		StandardClaims: jwt.StandardClaims{
			//现在+过期时间
			ExpiresAt: time.Now().Add(expireDuration).Unix(),
			Issuer:    "yanwei_xuexiao",
		},
		UserId: UserId,
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, user)
	return token.SignedString(secrite_key)
}

// 认证token
func AuthTokne(tokenString string, secreKey []byte) (*UserToken, error) {
	//解析token
	token, err := jwt.ParseWithClaims(tokenString, &UserToken{}, func(token *jwt.Token) (key interface{}, err error) {
		return secreKey, nil
	})
	if err != nil {
		return nil, err
	}

	clasims, is_ok := token.Claims.(*UserToken)
	//验证token
	if is_ok && token.Valid {
		return clasims, nil
	}
	return nil, errors.New("token valid err")
}

//type key int64
//
//const uidKey key = 0
//
//// 存入uid
//func Useruidcr(tokenString string, secreKey []byte) (*UserToken, error) {
//	//解析token
//	//// 将 uid 存入 context
//	ctx := context.WithValue(c.Request.Context(), uidKey, tokeninfo.UserId)
//	c.Request = c.Request.WithContext(ctx)
//}
